const {exec} = require('child_process');
const iconv = require('iconv-lite');

const encoding = 'cp936';
const binaryEncoding = 'binary';
const javaLibDir = './java-lib';

/**
 * Java工具类
 * Java类或Jar包只能放在/java-lib目录下
 */
class JavaUtils {
    /**
     * 运行Java类
     * @param {String} className Java类名
     * @returns {Promise<String>}
     */
    static exec(className) {
        return new Promise((resolve, reject) => {
            if (process.platform === 'win32') {
                exec(`java -classpath ${javaLibDir} ${className}`, {encoding: 'cp936'}, (err, stdout, stderr) => {
                    if (err) {
                        return reject(iconv.decode(new Buffer(stderr || err.message, binaryEncoding), encoding));
                    }
                    resolve(iconv.decode(new Buffer(stdout, binaryEncoding), encoding));
                });
            } else {
                exec(`java -classpath ${javaLibDir} ${className}`, (err, stdout, stderr) => {
                    if (err) {
                        return reject(err.message);
                    }
                    if (stderr) {
                        return reject(stderr);
                    }
                    resolve(stdout);
                });
            }
        });
    }
}

// module.exports = JavaUtils;
export default JavaUtils;